<template>
    <div class="poker-table">
      <div class="room-header">
        <h2>房间：{{ roomName }}</h2>
        <el-button
          type="primary"
          :disabled="!canStartGame"
          @click="startGame"
        >开始游戏</el-button>
        <el-button
          type="primary"
          :disabled="!canMakeFlop"
          @click="makeFlop"
        >发底牌</el-button>
        <el-button
          type="primary"
          :disabled="!canMakeTurn"
          @click="makeTurn"
        >发过牌</el-button>
        <el-button
          type="primary"
          :disabled="!canMakeRiver"
          @click="makeRiver"
        >发河牌</el-button>
        <el-button
          type="primary"
          :disabled="!canEndGame"
          @click="endGame"
        >结束游戏</el-button>
      </div>
      <div class="table-area">
        <div
          v-if="winnerPlayerNameList"
          class="winner-announcement"
        >
          获胜者：{{ winnerPlayerNameList }}
        </div>
        <div class="pot-money" v-if="money >= 0">底池：{{ money }}</div>
        <div class="player-circle">
          <div
            v-for="(player, idx) in players"
            :key="player.id"
            class="table-player"
            :class="getPlayerDirectionClass(idx, players.length)"
            :style="getPlayerPositionStyle(idx, players.length)"
          >
            <span style="white-space: nowrap;" v-if="getPlayerDirectionClass(idx, players.length) !== 'vertical'">{{ player.playerName }}</span>
            <span v-else class="vertical-text">{{ player.playerName }}</span>
            <div class="player-money-tag">
              {{ getPlayerGameMoney(player.playerId) }}
            </div>
          </div>
        </div>
        <div class="table-cards-area" v-if="tableCards.length"
             style="position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); z-index: 10;">
             <div class="poker-card" v-for="(card, idx) in tableCards" :key="idx" :class="'type-' + card.type">
            <div class="card-number top">{{ getCardNumber(card.number) }}</div>
            <div class="card-suit center">{{ getCardSuit(card.type) }}</div>
            <div class="card-number bottom">{{ getCardNumber(card.number) }}</div>
          </div>
        </div>
      </div>
      <div class="current-player">
        当前玩家：{{currentPlayerName}}
    </div>
    <div class="current-player">
        剩余金额：{{userMoney}}
    </div>
      <div class="action-area">
        <div class="hole-cards-side">
          <div class="hole-cards-area" v-if="holeCards.length">
            <div class="poker-card" v-for="(card, idx) in holeCards" :key="idx" :class="'type-' + card.type">
              <div class="card-number top">{{ getCardNumber(card.number) }}</div>
              <div class="card-suit center">{{ getCardSuit(card.type) }}</div>
              <div class="card-number bottom">{{ getCardNumber(card.number) }}</div>
            </div>
          </div>
        </div>
        <div class="action-controls" v-if="disPlayplayerAction">
            <div class="money-input">
              <el-button size="large" @click="changeMoney(-10)">-</el-button>
              <el-input-number
                v-model="playerMoney"
                :min="0"
                :step="1"
                size="large"
                style="width: 120px; margin: 0 12px; font-size: 22px;"
              />
              <el-button size="large" @click="changeMoney(10)">+</el-button>
            </div>
            <div class="action-buttons">
              <el-button size="large" @click="playerCheck">Check</el-button>
              <el-button size="large" @click="playerFold">Fold</el-button>
              <el-button size="large" type="primary" @click="playerRaise">Raise</el-button>
            </div>
          </div>
      </div>
    </div>
  </template>
  
  <script lang="ts" setup>
  import { ref, onMounted, onUnmounted, getCurrentInstance, computed, watch } from 'vue'
  import { useRoute } from 'vue-router'
  
  const route = useRoute()
  const roomId = route.params.roomId as string
  const currentPlayerName = sessionStorage.getItem('playerName')||''
  const roomName = route.params.roomName as string || ''
  const { proxy } = getCurrentInstance()!
  const $socket = (proxy as any).$socket
  
  const players = ref<any[]>([])
  const gameStart = ref(false)
  const holeCards = ref<any[]>([])
  const gamePlayerMoneyList = ref<any[]>([])
  const tableCards = ref<any[]>([])
  const playerMoney = ref<number>(0)
  const userMoney = ref<number>(0)
  const winnerPlayerNameList = ref<string>('')
  const money = ref<number>(0)
//   const winnerHoleCards = ref<any[]>([])
//   const playerBehaviorList = ref<any[]>([])
  
  function sendWhenReady(message: any) {
    if ($socket && $socket.readyState === 1) {
      $socket.send(JSON.stringify(message))
    } else if ($socket) {
      const handler = () => {
        $socket.send(JSON.stringify(message))
        $socket.removeEventListener('open', handler)
      }
      $socket.addEventListener('open', handler)
    } else {
      console.error('WebSocket 未初始化')
    }
  }

  function startGame() {
    sendWhenReady({
      event: 'startGame',
      data: { roomId }
    })
  }
  function makeFlop() {
    sendWhenReady({
      event: 'makeFlop',
      data: { gameId:sessionStorage.getItem('gameId') }
    })
  }
  function makeTurn() {
    sendWhenReady({
      event: 'makeTurn',
      data: { gameId:sessionStorage.getItem('gameId') }
    })
  }
    function makeRiver() {
        sendWhenReady({
        event: 'makeRiver',
        data: { gameId:sessionStorage.getItem('gameId') }
        })
    }
    function endGame() {
        sendWhenReady({
        event: 'endGame',
        data: { gameId:sessionStorage.getItem('gameId') }
        })
    }

  function getPlayerPositionStyle(idx: number, total: number) {
    // 主方向角度（以椭圆中心为原点，顺时针，单位：度）
    const mainAngles = [270, 0, 90, 180]; // 左、上、右、下
    const a = 400; // 椭圆长轴
    const b = 200; // 椭圆短轴

    let angle;
    if (total === 1) {
      angle = 0; // 只一个玩家，放正上
    } else if (total === 2) {
      angle = idx === 0 ? 0 : 180; // 上、下
    } else if (total === 3) {
      angle = [0, 90, 180][idx]; // 上、右、下
    } else if (total === 4) {
      angle = mainAngles[idx]; // 上、右、下、左
    } else {
      // 超过4人，主方向先分配，剩下的均匀插入主方向之间
      // 先分配主方向
      let angles = [...mainAngles];
      // 剩余玩家数
      const extra = total - 4;
      // 计算主方向之间的间隔
      for (let i = 0; i < extra; i++) {
        // 计算插入位置（主方向之间）
        const insertPos = Math.floor((i + 1) * (angles.length) / (extra + 1));
        // 计算插入角度（主方向之间的中点）
        const prev = angles[insertPos - 1];
        const next = angles[insertPos % angles.length];
        // 角度差，处理跨0°的情况
        let diff = next - prev;
        if (diff < -180) diff += 360;
        if (diff > 180) diff -= 360;
        const mid = prev + diff / 2;
        angles.splice(insertPos, 0, mid);
      }
      angle = angles[idx];
    }
    // 转换为弧度
    const rad = angle * Math.PI / 180;
    // 椭圆参数方程
    const x = Math.cos(rad) * a + a;
    const y = Math.sin(rad) * b + b;
    return {
      position: 'absolute',
      left: `${x}px`,
      top: `${y}px`,
      transform: 'translate(-50%, -50%)',
      background: '#fff',
      padding: '8px 16px',
      borderRadius: '16px',
      boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
      border: '2px solid #eee',
      minWidth: '80px',
      textAlign: 'center',
      zIndex: 2
    } as any
  }
  
  function getCardNumber(num: string) {
    if (num === '1') return 'A'
    if (num === '11') return 'J'
    if (num === '12') return 'Q'
    if (num === '13') return 'K'
    return num
  }
  function getCardSuit(type: number) {
    // 0: 红桃 ♥, 1: 黑桃 ♠, 2: 梅花 ♣, 3: 方片 ♦
    return ['♥', '♠', '♣', '♦'][type] || ''
  }
  
  $socket.onmessage = function(event: MessageEvent) {
    const msg = JSON.parse(event.data)
    switch (msg.event) {
      case 'updateGameState':
        players.value = msg.data
        gameStart.value = msg.gameState === '游戏中'
        holeCards.value = msg.holeCards || []
        tableCards.value = msg.tableCards || [] 
        winnerPlayerNameList.value = msg.winnerPlayerNameList || ""
        money.value = msg.money || 0
        userMoney.value = msg.userMoney || 0
        gamePlayerMoneyList.value = msg.gamePlayerMoneyList || []
        break
    }
  }

  
  onMounted(() => {
    const playerName = sessionStorage.getItem('playerName')
    if (roomId && playerName) {
      sendWhenReady({
        event: 'joinRoom',
        data: { roomId, playerName }
      })
    }
  })
  onUnmounted(() => {
    $socket.onmessage = null
  })

  // 计算属性：按钮可用性
  const disPlayplayerAction = computed(() => {
    return holeCards.value.length > 0
  })

  const canStartGame = computed(() => {
    return (holeCards.value.length === 0 && tableCards.value.length === 0)||(holeCards.value.length > 0 && tableCards.value.length === 5 && winnerPlayerNameList.value != '')
  })
  const canMakeFlop = computed(() => {
    return holeCards.value.length > 0 && tableCards.value.length === 0
  })
  const canMakeTurn = computed(() => {
    return holeCards.value.length > 0 && tableCards.value.length === 3
  })
  const canMakeRiver = computed(() => {
    return holeCards.value.length > 0 && tableCards.value.length === 4
  })
  const canEndGame = computed(() => {
    return (holeCards.value.length > 0 && tableCards.value.length === 5) && (winnerPlayerNameList.value === '')
  })

  // 监听players变化，初始化playerMoney

  function changeMoney(delta: number) {
    const val = playerMoney.value + delta
    playerMoney.value = val < 0 ? 0 : val
  }

  function playerCheck() {
    sendWhenReady({
      event: 'playerBehavior',
      data: {
        money: 0,
        behavior: 'check'
      }
    })
  }
  function playerFold() {
    sendWhenReady({
      event: 'playerBehavior',
      data: {
        money: 0,
        behavior: 'fold'
      }
    })
  }
  function playerRaise() {
    sendWhenReady({
      event: 'playerBehavior',
      data: {
        money: playerMoney.value,
        behavior: 'raise'
      }
    })
    playerMoney.value = 0 // 加注后清零
  }

  function getPlayerDirectionClass(idx: number, total: number) {
    // 只处理2~4人和5人以上主方向
    let angle = 0;
    if (total === 2) {
      angle = idx === 0 ? 0 : 180;
    } else if (total === 3) {
      angle = [0, 90, 180][idx];
    } else if (total === 4) {
      angle = [270, 0, 90, 180][idx];
    } else if (total > 4) {
      // 5人及以上，主方向为270(左)、0(上)、90(右)、180(下)
      const mainAngles = [270, 0, 90, 180];
      let angles = [...mainAngles];
      const extra = total - 4;
      for (let i = 0; i < extra; i++) {
        const insertPos = Math.floor((i + 1) * (angles.length) / (extra + 1));
        const prev = angles[insertPos - 1];
        const next = angles[insertPos % angles.length];
        let diff = next - prev;
        if (diff < -180) diff += 360;
        if (diff > 180) diff -= 360;
        const mid = prev + diff / 2;
        angles.splice(insertPos, 0, mid);
      }
      angle = angles[idx];
    }
    // 左右两侧
    if (angle === 90 || angle === 270) {
      return 'vertical';
    }
    return '';
  }

  function getPlayerGameMoney(playerId: number) {
    const found = gamePlayerMoneyList.value.find(item => item.playerId === playerId)
    return found ? found.gameMoney : 0
  }
  </script>
  
  <style scoped>
  .poker-table {
    max-width: 1100px;
    margin: 40px auto;
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0,0,0,0.12);
    padding: 48px;
  }
  .table-area {
    width: 800px;
    height: 400px;
    background: radial-gradient(ellipse at center, #2e8b57 70%, #145a32 100%);
    border-radius: 50% / 40%;
    margin: 40px auto 0 auto;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 8px 32px rgba(0,0,0,0.18), 0 0 0 8px #333 inset;
    border: 4px solid #333;
    position: relative;
  }
  .player-circle {
    position: absolute;
    left: 0; top: 0; right: 0; bottom: 0;
    width: 100%; height: 100%;
    pointer-events: none;
  }
  .table-player {
    pointer-events: auto;
    font-size: 18px;
    font-weight: bold;
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    border: 2px solid #eee;
    min-width: 80px;
    text-align: center;
    z-index: 2;
  }
  .table-player.self {
    background: #f0f9eb;
    border: 2px solid #67c23a;
  }
  .room-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 32px;
  }
  .room-header h2 {
    margin: 0;
  }
  .hole-cards-area {
    display: flex;
    justify-content: center;
    margin-top: 32px;
  }
  .table-cards-area {
    display: flex;
    justify-content: center;
    margin-top: 32px;
  }
  .poker-card {
    width: 60px;
    height: 90px;
    background: #fff;
    border-radius: 8px;
    border: 2px solid #bbb;
    margin: 0 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.10);
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    font-family: 'Arial', 'Helvetica', sans-serif;
  }
  .poker-card .card-number {
    font-size: 18px;
    font-weight: bold;
    position: absolute;
    left: 8px;
  }
  .poker-card .card-number.top {
    top: 6px;
  }
  .poker-card .card-number.bottom {
    bottom: 6px;
    right: 8px;
    left: auto;
  }
  .poker-card .card-suit {
    font-size: 28px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  .poker-card .card-suit.center {
    font-size: 28px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  .poker-card .card-suit.top-left {
    font-size: 16px;
    position: absolute;
    left: 8px;
    top: 28px;
  }
  .poker-card .card-suit.bottom-right {
    font-size: 16px;
    position: absolute;
    right: 8px;
    bottom: 28px;
  }
  .poker-card.type-0, .poker-card.type-3 {
    color: #d0021b; /* 红色 */
  }
  .poker-card.type-1, .poker-card.type-2 {
    color: #222; /* 黑色 */
  }
  .action-area {
    display: flex;
    justify-content: center;
    align-items: flex-start;
    margin-top: 32px;
    gap: 48px;
  }
  .hole-cards-side {
    margin-right: 48px;
    display: flex;
    align-items: center;
  }
  .action-controls {
    display: flex;
    flex-direction: column;
    gap: 24px;
  }
  .player-action {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 12px;
    background: #f9f9f9;
    border-radius: 12px;
    padding: 28px 36px;
    box-shadow: 0 4px 16px rgba(0,0,0,0.06);
  }
  .money-input {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    font-size: 22px;
  }
  .action-buttons {
    display: flex;
    gap: 16px;
  }
  .table-player.vertical .vertical-text {
    writing-mode: vertical-rl;
    text-orientation: mixed;
    letter-spacing: 2px;
    font-size: 18px;
    font-weight: bold;
    white-space: pre;
  }
  .winner-announcement {
    position: absolute;
    left: 50%;
    top: 32px;
    transform: translateX(-50%);
    background: linear-gradient(90deg, #f9d423 0%, #ff4e50 100%);
    color: #fff;
    font-size: 28px;
    font-weight: bold;
    padding: 12px 36px;
    border-radius: 24px;
    box-shadow: 0 4px 16px rgba(0,0,0,0.18);
    z-index: 100;
    letter-spacing: 2px;
    text-shadow: 0 2px 8px #ffb347, 0 1px 0 #fff;
    pointer-events: none;
  }
  .pot-money {
    position: absolute;
    left: 50%;
    top: calc(50% - 60px);
    transform: translate(-50%, -50%);
    background: linear-gradient(90deg, #ffe259 0%, #ffa751 100%);
    color: #222;
    font-size: 24px;
    font-weight: bold;
    padding: 10px 32px;
    border-radius: 20px;
    box-shadow: 0 4px 16px rgba(0,0,0,0.15);
    border: 2px solid #fffbe6;
    z-index: 99;
    letter-spacing: 2px;
    text-shadow: 0 1px 4px #fffbe6, 0 1px 0 #fff;
    pointer-events: none;
  }
  .player-money-tag {
    margin-top: 6px;
    background: linear-gradient(90deg, #ffe259 0%, #ffa751 100%);
    color: #222;
    font-size: 16px;
    font-weight: bold;
    padding: 2px 14px;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.10);
    border: 1.5px solid #fffbe6;
    display: inline-block;
    min-width: 40px;
    text-align: center;
    letter-spacing: 1px;
  }
  </style>